package modules

import (
	"InstantCommunication/utils"
	"fmt"
	"gorm.io/gorm"
	"time"
)

type UserBasic struct {
	ID            uint           `gorm:"primaryKey" json:"id"`
	CreatedAt     time.Time      `json:"-"`
	UpdatedAt     time.Time      `json:"-"`
	DeletedAt     gorm.DeletedAt `gorm:"index"`
	Name          string         `json:"name" binding:"required"`
	Password      string         `json:"password" binding:"required"`
	Salt          string         `json:"-"`
	Phone         string         `json:"phone" binding:"required,validPhone"`
	Email         string         `json:"email" binding:"required,email"`
	Identity      string         `json:"identity"`
	ClientPort    string         `json:"client_port"`
	ClientIP      string         `json:"client_ip"`
	LoginTime     time.Time      `json:"login_time"`
	HeartbeatTime time.Time      `json:"heartbeat_time"`
	LogoutTime    time.Time      `json:"logout_time"`
	IsLogout      bool           `json:"is_logout"`
	DeviceInfo    string         `json:"device_info"`
}

func (table *UserBasic) TableName() string {
	return "user_basic"
}

func GetUserList() []*UserBasic {
	data := make([]*UserBasic, 10)
	utils.DB.Find(&data)
	for _, v := range data {
		fmt.Println(v)
	}
	return data
}

func FindUserByName(name string) UserBasic {
	user := UserBasic{}
	utils.DB.Where("name = ?", name).First(&user)
	return user
}

func FindUserByNameAndPassword(name, password string) UserBasic {
	user := UserBasic{}
	utils.DB.Where("name = ? and password = ?", name, password).First(&user)

	//token加密
	str := fmt.Sprintf("%d", time.Now().Unix())
	temp := utils.MD5Encode(str)
	utils.DB.Model(&user).Where("id = ?", user.ID).Update("identity", temp)
	return user
}

func FindUserByPhone(phone string) *gorm.DB {
	user := UserBasic{}
	return utils.DB.Where("phone = ?", phone).First(&user)
}
func FindUserByEmail(email string) *gorm.DB {
	user := UserBasic{}
	return utils.DB.Where("email = ?", email).First(&user)
}

func CreateUser(user UserBasic) *gorm.DB { return utils.DB.Create(&user) }

func DeleteUser(user UserBasic) *gorm.DB { return utils.DB.Delete(&user) }

func UpdateUser(user UserBasic) *gorm.DB {
	return utils.DB.Model(&user).Updates(UserBasic{Name: user.Name, Password: user.Password, Phone: user.Phone, Email: user.Email})
}
